package com.jjlin.chapter_3;

import java.util.*;

public class CD172{
    //二叉树节点
    public static class TreeNode{
        public int val;
        public TreeNode left;
        public TreeNode right;
        public TreeNode(int data){
            this.val = data;
        }
    }

    //建立二叉树
    public static TreeNode createBinaryTree(int[][] nums, int root){
        HashMap<Integer, TreeNode> map = new HashMap<>();
        int rows = nums.length;
        int cols = nums[0].length;
        for(int i = 0; i < rows; i++)
            for(int j = 0; j < cols; j++)
                if(nums[i][j] != 0 && !map.containsKey(nums[i][j]))
                    map.put(nums[i][j], new TreeNode(nums[i][j]));

        for(int i = 0; i < rows; i++){
            TreeNode node = map.get(nums[i][0]);
            if(nums[i][1] != 0){
                node.left = map.get(nums[i][1]);
            }
            if(nums[i][2] != 0){
                node.right = map.get(nums[i][2]);
            }
        }
        return map.get(root);
    }

    //判断是否为平衡二叉树
    public static boolean isBalance(TreeNode node){
        boolean[] res = new boolean[1];//相当于一个全局变量
        res[0] = true;
        getHeight(node, 1, res);
        return res[0];
    }

    public static int getHeight(TreeNode node, int level, boolean[] res){
        if(node == null)
            return level;
        int leftH = getHeight(node.left, level + 1, res);
        if(!res[0])
            return leftH;
        int rightH = getHeight(node.right, level + 1, res);
        if(!res[0])
            return rightH;
        if(Math.abs(leftH - rightH) > 1)
            res[0] = false;
        return Math.max(leftH, rightH);
    }

    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int root = sc.nextInt();
        int[][] nums = new int[n][3];
        for(int i = 0; i < n; i++)
            for(int j = 0; j < 3; j++)
                nums[i][j] = sc.nextInt();
        TreeNode head = createBinaryTree(nums, root);
        System.out.println(isBalance(head));
    }
}



